package listbyorder.access101_200.test110;

import listbyorder.utils.TreeNode;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/6/7 10:50
 */
public class Solution2 {

    // 方法2————以前的解法，属性 DP 问题套路
    public boolean isBalanced(TreeNode root) {
        return getAns(root).isAvl;
    }

    private Result getAns(TreeNode root) {
        if (root == null) return new Result(true, 0);
        Result left = getAns(root.left);
        Result right = getAns(root.right);
        if (left.isAvl && right.isAvl && Math.abs(left.height - right.height) < 2) {
            return new Result(true, Math.max(left.height, right.height) + 1);
        } else {
            return new Result(false, 0);
        }
    }

    class Result {
        boolean isAvl;
        int height;

        public Result(boolean isAvl, int height) {
            this.isAvl = isAvl;
            this.height = height;
        }
    }
}
